################################

library('Matrix')
library('lme4')
library('ggplot2')
library('tidyverse')
library(lmerTest)
library(dplyr)
library('corrr')
library(tidyverse)
library(FactoMineR)
library(factoextra)
library(psych)
library('MuMIn')
library(performance)
library(interactions)

setwd('')
df = read.csv(file="", header=TRUE, sep=";")
df <- subset(df, Status != "EXCLUDED")
#Exclude participants that gave uniform responses
df <- subset(df, ID != 179)
df$Scenario <- as.factor(df$Scenario)
df$Source <- as.factor(df$Source)
df$Group <- as.factor(df$Group)
df$cultureIA_Freq1 <- as.numeric(df$cultureIA_Freq1)
df$cultureIA_competence <- as.numeric(df$cultureIA_competence)
df$Q3_stake <- as.numeric(df$Q3_stake)
df$trustAI_T <- as.numeric(df$trustAI_T)

#EXCLUSION CALCULATION
df$TimeTotal_min <- as.numeric(gsub(",", ".", df$TimeTotal_min))
df$LogTime <- log(df$TimeTotal_min)
# Compute mean and standard deviation TIME
mean_time <- mean(df$LogTime, na.rm = TRUE)
sd_time <- sd(df$LogTime, na.rm = TRUE)
# Filter values within ±2.5 SD TIME
df <- df %>%
  filter(LogTime > (mean_time - 2.5 * sd_time) & LogTime < (mean_time + 2.5 * sd_time))

group_distribution <- df %>%
  group_by(Group) %>%
  summarise(unique_participants = n_distinct(ID))

df$Source <- factor(df$Source, levels = c("Expert", "NExpert","AI"))

# Composite score "TRUST"
df_items <- df[, c("trustIA_1", "trustIA_2", "trustIA_3", "trustIA_5", "trustIA_6Transformed")]
# Calcul de Cronbach's alpha pour les items 1 à 5
alpha_result <- alpha(df_items)
print(alpha_result)
####ANALISI PCA
df_pca <- df %>% select(trustIA_1, trustIA_2, trustIA_3, trustIA_5, trustIA_6Transformed)
# Run PCA (standardized)
pca_result <- prcomp(df_pca, center = TRUE, scale. = TRUE)
# Summary of variance explained
summary(pca_result)
print(pca_result$rotation)
# Scree plot to decide number of PCs to keep
fviz_eig(pca_result)
# Variable contributions to components
fviz_pca_var(pca_result, col.var = "cos2")
# Extract PCA scores
pc_scores <- as.data.frame(pca_result$x)
# Add PCA scores to original dataset
df <- cbind(df, pc_scores)
fviz_eig(pca_result,
         addlabels = TRUE,
         ylim = c(0, 80),
         barfill = "steelblue",
         barcolor = "black",
         main = "Scree Plot: Variance Explained by Principal Components")

mixM1_truth <- lmer(Q1_truth ~ Source + Source:trustAI_T + Source:cultureIA_competence + Source:Q3_stake + Source:cultureIA_Freq1 + (1|ID), data = df)
summary(mixM1_truth)

mixM1_inclusion <-lmer(Q2_inclusion ~Source + Source:trustAI_T + Source:cultureIA_competence + Source:Q3_stake + Source:cultureIA_Freq1 + (1|ID), data = df)
summary(mixM1_inclusion)

check_collinearity(mixM1_truth)

#center continuous predictors to avoid multicollinearity
df$trustAI_T_c <- scale(df$trustAI_T, center = TRUE, scale = FALSE)
df$cultureIA_competence_c <- scale(df$cultureIA_competence, center = TRUE, scale = FALSE)
df$Q3_stake_c <- scale(df$Q3_stake, center = TRUE, scale = FALSE)
df$cultureIA_Freq1_c <- scale(df$cultureIA_Freq1, center = TRUE, scale = FALSE)

mixM1_truth_c <- lmer(Q1_truth ~ Source + Source:trustAI_T_c + Source:cultureIA_competence_c + Source:Q3_stake_c + Source:cultureIA_Freq1_c + (1|ID), data = df)
summary(mixM1_truth_c)

r.squaredGLMM(mixM1_truth_c)

mixM1_inclusion_c <-lmer(Q2_inclusion ~Source + Source:trustAI_T_c + Source:cultureIA_competence_c + Source:Q3_stake_c + Source:cultureIA_Freq1_c + (1|ID), data = df)
summary(mixM1_inclusion_c)

r.squaredGLMM(mixM1_inclusion_c)

# Visualization "should trust this info"

df %>%
  group_by(Source) %>%
  summarize(MeanRating = mean(Q1_truth, na.rm = TRUE),
            SD = sd(Q1_truth, na.rm = TRUE),
            Count = n())

ggplot(df, aes(x = Source, y = Q1_truth)) +
  geom_boxplot(aes(fill = Source), outlier.shape = NA, alpha = 0.7) +
  geom_jitter(aes(color = Source), width = 0.2, alpha = 0.4) +
  scale_fill_brewer(palette = "Dark2") +
  scale_color_brewer(palette = "Dark2") +
  labs(title = "",
       x = "",
       y = "Information Truthfulness") +
  theme_minimal() +
  theme(legend.position = "none")  # remove if you want to hide legend

ggsave("InformationTrust_Source.png", width = 7, height = 5, dpi = 300)

# INTERACTION SOURCE*FREQUENCY
p <- interact_plot(mixM1_truth,
                   pred = cultureIA_Freq1,
                   modx = Source,
                   plot.points = FALSE,
                   interval = TRUE,
                   colors = "Dark2")
# Modifica le linee manualmente
p <- p + 
  theme_minimal() +
  labs(x = "Frequency of ChatGPT use",
       y = "Information Truthfulness",
       color = "Source") +
  theme(legend.key.width = unit(2, "lines"))
# Forza tutte le linee a essere solide
p$layers[[1]]$aes_params$linetype <- "solid"  # linea di regressione
p$layers[[2]]$aes_params$linetype <- "blank"  # bordi intervallo di confidenza
p
ggsave("InformationTrust_Source_Frequency.png", width = 7, height = 5, dpi = 300)

# INTERACTION SOURCE*COMPETENCE
p <- interact_plot(mixM1_truth,
                   pred = cultureIA_competence,
                   modx = Source,
                   plot.points = FALSE,
                   interval = TRUE,
                   colors = "Dark2")
# Modifica le linee manualmente
p <- p + 
  theme_minimal() +
  labs(x = "Competence of AI",
       y = "Information Truthfulness",
       color = "Source") +
  theme(legend.key.width = unit(2, "lines"))
# Forza tutte le linee a essere solide
p$layers[[1]]$aes_params$linetype <- "solid"  # linea di regressione
p$layers[[2]]$aes_params$linetype <- "blank"  # bordi intervallo di confidenza
p
ggsave("InformationTrust_Source_Competence.png", width = 7, height = 5, dpi = 300)

# INTERACTION SOURCE*TRUST
p <- interact_plot(mixM1_truth,
                   pred = trustAI_T,
                   modx = Source,
                   plot.points = FALSE,
                   interval = TRUE,
                   colors = "Dark2")
# Modifica le linee manualmente
p <- p + 
  theme_minimal() +
  labs(x = "Global AI Trust",
       y = "Information Truthfulness",
       color = "Source") +
  theme(legend.key.width = unit(2, "lines"))
# Forza tutte le linee a essere solide
p$layers[[1]]$aes_params$linetype <- "solid"  # linea di regressione
p$layers[[2]]$aes_params$linetype <- "blank"  # bordi intervallo di confidenza
p
ggsave("InformationTrust_Source_Trust.png", width = 7, height = 5, dpi = 300)

# INTERACTION SOURCE*Stakes
p <- interact_plot(mixM1_truth,
                   pred = Q3_stake,
                   modx = Source,
                   plot.points = FALSE,
                   interval = TRUE,
                   colors = "Dark2")
# Modifica le linee manualmente
p <- p + 
  theme_minimal() +
  labs(x = "Stakes",
       y = "Information Truthfulness",
       color = "Source") +
  theme(legend.key.width = unit(2, "lines"))
# Forza tutte le linee a essere solide
p$layers[[1]]$aes_params$linetype <- "solid"  # linea di regressione
p$layers[[2]]$aes_params$linetype <- "blank"  # bordi intervallo di confidenza
p
ggsave("InformationTrust_Source_Stakes.png", width = 7, height = 5, dpi = 300)


# VISUALIZATION: "should include this info"

df %>%
  group_by(Source) %>%
  summarize(MeanRating = mean(Q2_inclusion, na.rm = TRUE),
            SD = sd(Q1_truth, na.rm = TRUE),
            Count = n())

ggplot(df, aes(x = Source, y = Q1_truth)) +
  geom_boxplot(aes(fill = Source), outlier.shape = NA, alpha = 0.7) +
  geom_jitter(aes(color = Source), width = 0.2, alpha = 0.4) +
  scale_fill_brewer(palette = "Dark2") +
  scale_color_brewer(palette = "Dark2") +
  labs(title = "",
       x = "",
       y = "Professional Use") +
  theme_minimal() +
  theme(legend.position = "none")  # remove if you want to hide legend

ggsave("ProfessionalUse_Source.png", width = 7, height = 5, dpi = 300)

# INTERACTION SOURCE*TRUST
p <- interact_plot(mixM1_inclusion,
                   pred = trustAI_T,
                   modx = Source,
                   plot.points = FALSE,
                   interval = TRUE,
                   colors = "Dark2")
# Modifica le linee manualmente
p <- p + 
  theme_minimal() +
  labs(x = "Global AI Trust",
       y = "Professional Use",
       color = "Source") +
  theme(legend.key.width = unit(2, "lines"))
# Forza tutte le linee a essere solide
p$layers[[1]]$aes_params$linetype <- "solid"  # linea di regressione
p$layers[[2]]$aes_params$linetype <- "blank"  # bordi intervallo di confidenza
p
ggsave("ProfessionalUse_Source_Trust.png", width = 7, height = 5, dpi = 300)

# INTERACTION SOURCE*Stakes
p <- interact_plot(mixM1_inclusion,
                   pred = Q3_stake,
                   modx = Source,
                   plot.points = FALSE,
                   interval = TRUE,
                   colors = "Dark2")
# Modifica le linee manualmente
p <- p + 
  theme_minimal() +
  labs(x = "Stakes",
       y = "Porfessional Use",
       color = "Source") +
  theme(legend.key.width = unit(2, "lines"))
# Forza tutte le linee a essere solide
p$layers[[1]]$aes_params$linetype <- "solid"  # linea di regressione
p$layers[[2]]$aes_params$linetype <- "blank"  # bordi intervallo di confidenza
p
ggsave("ProfessionalUse_Source_Stakes.png", width = 7, height = 5, dpi = 300)

# INTERACTION SOURCE*FREQUENCY
p <- interact_plot(mixM1_inclusion,
                   pred = cultureIA_Freq1,
                   modx = Source,
                   plot.points = FALSE,
                   interval = TRUE,
                   colors = "Dark2")
# Modifica le linee manualmente
p <- p + 
  theme_minimal() +
  labs(x = "Frequency of ChatGPT use",
       y = "Professional Use",
       color = "Source") +
  theme(legend.key.width = unit(2, "lines"))
# Forza tutte le linee a essere solide
p$layers[[1]]$aes_params$linetype <- "solid"  # linea di regressione
p$layers[[2]]$aes_params$linetype <- "blank"  # bordi intervallo di confidenza
p
ggsave("ProfessionalUse_Source_Frequency.png", width = 7, height = 5, dpi = 300)

# INTERACTION SOURCE*COMPETENCE
p <- interact_plot(mixM1_inclusion,
                   pred = cultureIA_competence,
                   modx = Source,
                   plot.points = FALSE,
                   interval = TRUE,
                   colors = "Dark2")
# Modifica le linee manualmente
p <- p + 
  theme_minimal() +
  labs(x = "Competence of AI",
       y = "Professional Use",
       color = "Source") +
  theme(legend.key.width = unit(2, "lines"))
# Forza tutte le linee a essere solide
p$layers[[1]]$aes_params$linetype <- "solid"  # linea di regressione
p$layers[[2]]$aes_params$linetype <- "blank"  # bordi intervallo di confidenza
p
ggsave("ProfessionalUse_Source_Competence.png", width = 7, height = 5, dpi = 300)
